//package com.jxw.cloudpen.web.websockethandler;/**
// * Created by by on 2020/11/13 10:35
// */
//
//import com.google.api.gax.rpc.ClientStream;
//import com.google.api.gax.rpc.ResponseObserver;
//import com.google.api.gax.rpc.StreamController;
//import com.google.cloud.speech.v1p1beta1.*;
//import com.google.protobuf.ByteString;
//import com.google.protobuf.Duration;
//import com.jxw.cloudpen.web.netty.Entity.StreamData;
//import com.jxw.cloudpen.web.netty.common.LocalSession;
//import com.jxw.cloudpen.web.netty.google.InfiniteStreamRecognize6;
//import com.jxw.cloudpen.web.netty.google.StreamRecognManager;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import java.io.IOException;
//import java.text.DecimalFormat;
//import java.util.ArrayList;
//import java.util.concurrent.Callable;
//import java.util.concurrent.TimeUnit;
//
///**
// * invok异步执行
// *
// * @program: sxreader_rpc
// * @author: ligang
// * @create: 2020-11-13 10:35
// */
//public class ServiceBusinCallable implements Callable<StreamData> {
//    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceBusinCallable.class);
//    private StreamData message;
//    private LocalSession session;
//
//
//    private static final int STREAMING_LIMIT = 290000; // ~5 minutes
//
//    public static final String RED = "\033[0;31m";
//    public static final String GREEN = "\033[0;32m";
//    public static final String YELLOW = "\033[0;33m";
//
//    // Creating shared object
//    private static int BYTES_PER_BUFFER = 6400; // buffer size in bytes
//
//    private static int restartCounter = 0;
//    private static ArrayList<ByteString> audioInput = new ArrayList<ByteString>();
//    private static ArrayList<ByteString> lastAudioInput = new ArrayList<ByteString>();
//    private static int resultEndTimeInMS = 0;
//    private static int isFinalEndTime = 0;
//    private static int finalRequestEndTime = 0;
//    private static boolean newStream = true;
//    private static double bridgingOffset = 0;
//    private static boolean lastTranscriptWasFinal = false;
//    private static StreamController referenceToStreamController;
//    private static ByteString tempByteString;
//
//
//    public ServiceBusinCallable(StreamData message, LocalSession localSession) {
//        this.message = message;
//        this.session = localSession;
//    }
//
//    @Override
//    public StreamData call() throws Exception {
////        StreamData responseMsg = new StreamData();
////        InfiniteStreamRecognize5 infiniteStreamRecognize4 = StreamRecognManager.map.get(message.getClientId());
////        try {
////            //初始化netty 服务端
//////            InfiniteStreamRecognizeOptions options = InfiniteStreamRecognizeOptions.fromFlags(args);
//////            if (options == null) {
//////                // Could not parse.
//////                System.out.println("Failed to parse options.");
//////                System.exit(1);
//////            }
////
////            try {
////                InfiniteStreamRecognize4.infiniteStreamingRecognize( "en-US");
////            } catch (Exception e) {
////                System.out.println("Exception caught: " + e);
////            }
////        } catch (Exception e) {
////            System.out.println("Exception caught: " + e);
////        }
//
//
////        if(infiniteStreamRecognize4==null){
////            //action
////            try {
////                infiniteStreamRecognize4 = new InfiniteStreamRecognize5();
////                infiniteStreamRecognize4.infiniteStreamingRecognize( "en-US");
////                StreamRecognManager.map.put(message.getClientId(),infiniteStreamRecognize4);
////            } catch (Exception e) {
////                System.out.println("Exception caught: " + e);
////            }
////        }
////        infiniteStreamRecognize4.sharedQueue.put(message.getData());
//
//        synchronized (message.getClientId()){
//            InfiniteStreamRecognize6 infiniteStreamRecognize6 = StreamRecognManager.map.get(message.getClientId());
//
//            if(infiniteStreamRecognize6!=null){
//                infiniteStreamRecognize6.sharedQueue.put(message.getData());
//            }
////            InfiniteStreamRecognize6.sharedQueue.put(message.getData());
//        }
//
//        return null;
//    }
//
//
//    public static String convertMillisToDate(double milliSeconds) {
//        long millis = (long) milliSeconds;
//        DecimalFormat format = new DecimalFormat();
//        format.setMinimumIntegerDigits(2);
//        return String.format(
//                "%s:%s /",
//                format.format(TimeUnit.MILLISECONDS.toMinutes(millis)),
//                format.format(
//                        TimeUnit.MILLISECONDS.toSeconds(millis)
//                                - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))));
//    }
//
//
//    public ClientStream<StreamingRecognizeRequest> getClientStream(String languageCode) {
//
//        ResponseObserver<StreamingRecognizeResponse> responseObserver = null;
//        try (SpeechClient client = SpeechClient.create()) {
//            ClientStream<StreamingRecognizeRequest> clientStream;
//            responseObserver =
//                    new ResponseObserver<StreamingRecognizeResponse>() {
//
//                        ArrayList<StreamingRecognizeResponse> responses = new ArrayList<>();
//
//                        public void onStart(StreamController controller) {
//                            referenceToStreamController = controller;
//                        }
//
//                        public void onResponse(StreamingRecognizeResponse response) {
//                            responses.add(response);
//                            StreamingRecognitionResult result = response.getResultsList().get(0);
//                            Duration resultEndTime = result.getResultEndTime();
//                            resultEndTimeInMS =
//                                    (int)
//                                            ((resultEndTime.getSeconds() * 1000) + (resultEndTime.getNanos() / 1000000));
//                            double correctedTime =
//                                    resultEndTimeInMS - bridgingOffset + (STREAMING_LIMIT * restartCounter);
//
//                            SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
//                            if (result.getIsFinal()) {
//                                System.out.println("识别成功");
//                                System.out.print(GREEN);
//                                System.out.print("\033[2K\r");
//                                System.out.printf(
//                                        "%s: %s [confidence: %.2f]\n",
//                                        convertMillisToDate(correctedTime),
//                                        alternative.getTranscript(),
//                                        alternative.getConfidence());
//                                isFinalEndTime = resultEndTimeInMS;
//                                lastTranscriptWasFinal = true;
//
//                                //识别结果
//                                String speedMsg = alternative.getTranscript();
//                            } else {
//                                System.out.print(RED);
//                                System.out.print("\033[2K\r");
//                                System.out.printf(
//                                        "%s: %s", convertMillisToDate(correctedTime), alternative.getTranscript());
//                                lastTranscriptWasFinal = false;
//                            }
//                        }
//
//                        public void onComplete() {
//                        }
//
//                        public void onError(Throwable t) {
//                            t.printStackTrace();
//                        }
//                    };
//
//
//            clientStream = client.streamingRecognizeCallable().splitCall(responseObserver);
//
//            RecognitionConfig recognitionConfig =
//                    RecognitionConfig.newBuilder()
//                            .setEncoding(RecognitionConfig.AudioEncoding.LINEAR16)
//                            .setLanguageCode(languageCode)
//                            .setSampleRateHertz(16000)
//                            .build();
//
//            StreamingRecognitionConfig streamingRecognitionConfig =
//                    StreamingRecognitionConfig.newBuilder()
//                            .setConfig(recognitionConfig)
//                            .setInterimResults(true)
//                            .build();
//
//            StreamingRecognizeRequest request =
//                    StreamingRecognizeRequest.newBuilder()
//                            .setStreamingConfig(streamingRecognitionConfig)
//                            .build(); // The first request in a streaming call has to be a config
//
//            clientStream.send(request);
//
//            return clientStream;
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        return null;
//    }
//
//    public String executeStr(ClientStream<StreamingRecognizeRequest> clientStream, byte[] bytes) {
//
//        try {
//            StreamingRecognizeRequest request;
//            long startTime = System.currentTimeMillis();
//            while (true) {
//
//                long estimatedTime = System.currentTimeMillis() - startTime;
//
//                if (estimatedTime >= STREAMING_LIMIT) {
//
//                    //关闭
//
//                    clientStream.closeSend();
//                    referenceToStreamController.cancel(); // remove Observer
//
//                    if (resultEndTimeInMS > 0) {
//                        finalRequestEndTime = isFinalEndTime;
//                    }
//                    resultEndTimeInMS = 0;
//
//                    lastAudioInput = null;
//                    lastAudioInput = audioInput;
//                    audioInput = new ArrayList<ByteString>();
//
//                    restartCounter++;
//
//                    if (!lastTranscriptWasFinal) {
//                        System.out.print('\n');
//                    }
//
//                    newStream = true;
//
////                   clientStream = client.streamingRecognizeCallable().splitCall(responseObserver);
////
////                   request =
////                           StreamingRecognizeRequest.newBuilder()
////                                   .setStreamingConfig(streamingRecognitionConfig)
////                                   .build();
//
//                    System.out.println(YELLOW);
//                    System.out.printf("%d: RESTARTING REQUEST\n", restartCounter * STREAMING_LIMIT);
//
//                    startTime = System.currentTimeMillis();
//
//                } else {
//                    if ((newStream) && (lastAudioInput.size() > 0)) {
//                        // if this is the first audio from a new request
//                        // calculate amount of unfinalized audio from last request
//                        // resend the audio to the speech client before incoming audio
//                        double chunkTime = STREAMING_LIMIT / lastAudioInput.size();
//                        // ms length of each chunk in previous request audio arrayList
//                        if (chunkTime != 0) {
//                            if (bridgingOffset < 0) {
//                                // bridging Offset accounts for time of resent audio
//                                // calculated from last request
//                                bridgingOffset = 0;
//                            }
//                            if (bridgingOffset > finalRequestEndTime) {
//                                bridgingOffset = finalRequestEndTime;
//                            }
//                            int chunksFromMs =
//                                    (int) Math.floor((finalRequestEndTime - bridgingOffset) / chunkTime);
//                            // chunks from MS is number of chunks to resend
//                            bridgingOffset =
//                                    (int) Math.floor((lastAudioInput.size() - chunksFromMs) * chunkTime);
//                            // set bridging offset for next request
//                            for (int i = chunksFromMs; i < lastAudioInput.size(); i++) {
//                                request =
//                                        StreamingRecognizeRequest.newBuilder()
//                                                .setAudioContent(lastAudioInput.get(i))
//                                                .build();
//                                clientStream.send(request);
//                            }
//                        }
//                        newStream = false;
//                    }
//
////                   tempByteString = ByteString.copyFrom(sharedQueue.take());
//
//
//                    tempByteString = ByteString.copyFrom(bytes);
//                    request =
//                            StreamingRecognizeRequest.newBuilder().setAudioContent(tempByteString).build();
//
//                    audioInput.add(tempByteString);
//                }
//
//
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            System.out.println(e);
//        }
//        return null;
//    }
//
//    /**
//     * Performs infinite streaming speech recognition
//     */
//    public static void infiniteStreamingRecognize(String languageCode, byte[] bytes) throws Exception {
//
//        ResponseObserver<StreamingRecognizeResponse> responseObserver = null;
//        try (SpeechClient client = SpeechClient.create()) {
//            ClientStream<StreamingRecognizeRequest> clientStream;
//            responseObserver =
//                    new ResponseObserver<StreamingRecognizeResponse>() {
//
//                        ArrayList<StreamingRecognizeResponse> responses = new ArrayList<>();
//
//                        public void onStart(StreamController controller) {
//                            referenceToStreamController = controller;
//                        }
//
//                        public void onResponse(StreamingRecognizeResponse response) {
//                            responses.add(response);
//                            StreamingRecognitionResult result = response.getResultsList().get(0);
//                            Duration resultEndTime = result.getResultEndTime();
//                            resultEndTimeInMS =
//                                    (int)
//                                            ((resultEndTime.getSeconds() * 1000) + (resultEndTime.getNanos() / 1000000));
//                            double correctedTime =
//                                    resultEndTimeInMS - bridgingOffset + (STREAMING_LIMIT * restartCounter);
//
//                            SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
//                            if (result.getIsFinal()) {
//                                System.out.println("识别成功");
//                                System.out.print(GREEN);
//                                System.out.print("\033[2K\r");
//                                System.out.printf(
//                                        "%s: %s [confidence: %.2f]\n",
//                                        convertMillisToDate(correctedTime),
//                                        alternative.getTranscript(),
//                                        alternative.getConfidence());
//                                isFinalEndTime = resultEndTimeInMS;
//                                lastTranscriptWasFinal = true;
//
//                                //识别结果
//                                String speedMsg = alternative.getTranscript();
//                            } else {
//                                System.out.print(RED);
//                                System.out.print("\033[2K\r");
//                                System.out.printf(
//                                        "%s: %s", convertMillisToDate(correctedTime), alternative.getTranscript());
//                                lastTranscriptWasFinal = false;
//                            }
//                        }
//
//                        public void onComplete() {
//                        }
//
//                        public void onError(Throwable t) {
//                            t.printStackTrace();
//                        }
//                    };
//
//
//            clientStream = client.streamingRecognizeCallable().splitCall(responseObserver);
//
//            RecognitionConfig recognitionConfig =
//                    RecognitionConfig.newBuilder()
//                            .setEncoding(RecognitionConfig.AudioEncoding.LINEAR16)
//                            .setLanguageCode(languageCode)
//                            .setSampleRateHertz(16000)
//                            .build();
//
//            StreamingRecognitionConfig streamingRecognitionConfig =
//                    StreamingRecognitionConfig.newBuilder()
//                            .setConfig(recognitionConfig)
//                            .setInterimResults(true)
//                            .build();
//
//            StreamingRecognizeRequest request =
//                    StreamingRecognizeRequest.newBuilder()
//                            .setStreamingConfig(streamingRecognitionConfig)
//                            .build(); // The first request in a streaming call has to be a config
//
//            clientStream.send(request);
//
//
//            try {
//                long startTime = System.currentTimeMillis();
//                while (true) {
//
//                    long estimatedTime = System.currentTimeMillis() - startTime;
//
//                    if (estimatedTime >= STREAMING_LIMIT) {
//
//                        //关闭
//
//                        clientStream.closeSend();
//                        referenceToStreamController.cancel(); // remove Observer
//
//                        if (resultEndTimeInMS > 0) {
//                            finalRequestEndTime = isFinalEndTime;
//                        }
//                        resultEndTimeInMS = 0;
//
//                        lastAudioInput = null;
//                        lastAudioInput = audioInput;
//                        audioInput = new ArrayList<ByteString>();
//
//                        restartCounter++;
//
//                        if (!lastTranscriptWasFinal) {
//                            System.out.print('\n');
//                        }
//
//                        newStream = true;
//
//                        clientStream = client.streamingRecognizeCallable().splitCall(responseObserver);
//
//                        request =
//                                StreamingRecognizeRequest.newBuilder()
//                                        .setStreamingConfig(streamingRecognitionConfig)
//                                        .build();
//
//                        System.out.println(YELLOW);
//                        System.out.printf("%d: RESTARTING REQUEST\n", restartCounter * STREAMING_LIMIT);
//
//                        startTime = System.currentTimeMillis();
//
//                    } else {
//
//                        if ((newStream) && (lastAudioInput.size() > 0)) {
//                            // if this is the first audio from a new request
//                            // calculate amount of unfinalized audio from last request
//                            // resend the audio to the speech client before incoming audio
//                            double chunkTime = STREAMING_LIMIT / lastAudioInput.size();
//                            // ms length of each chunk in previous request audio arrayList
//                            if (chunkTime != 0) {
//                                if (bridgingOffset < 0) {
//                                    // bridging Offset accounts for time of resent audio
//                                    // calculated from last request
//                                    bridgingOffset = 0;
//                                }
//                                if (bridgingOffset > finalRequestEndTime) {
//                                    bridgingOffset = finalRequestEndTime;
//                                }
//                                int chunksFromMs =
//                                        (int) Math.floor((finalRequestEndTime - bridgingOffset) / chunkTime);
//                                // chunks from MS is number of chunks to resend
//                                bridgingOffset =
//                                        (int) Math.floor((lastAudioInput.size() - chunksFromMs) * chunkTime);
//                                // set bridging offset for next request
//                                for (int i = chunksFromMs; i < lastAudioInput.size(); i++) {
//                                    request =
//                                            StreamingRecognizeRequest.newBuilder()
//                                                    .setAudioContent(lastAudioInput.get(i))
//                                                    .build();
//                                    clientStream.send(request);
//                                }
//                            }
//                            newStream = false;
//                        }
//
//                        tempByteString = ByteString.copyFrom(bytes);
//
//                        request =
//                                StreamingRecognizeRequest.newBuilder().setAudioContent(tempByteString).build();
//
//                        audioInput.add(tempByteString);
//                    }
//
//                    clientStream.send(request);
//                }
//            } catch (Exception e) {
//                System.out.println(e);
//            }
//        }
//
//
//    }
//
//
//}
